#include "game_map.h"

#include <iostream>
#include <string>

#include "log.h"


GameMap::GameMap(int type_id, int unique_id): type_id_(type_id), unique_id_(unique_id){}

GameMap::~GameMap(){}


void GameMap::Init(int length, int width){
    length_ = length;
    width_ = width;

    map_.resize(width + 1, std::vector<int>(length + 1, 0));
    player2pos_.clear();
}

void GameMap::AddPlayer(int player_id, int x, int y){
    if(x > length_ || y > width_){
        return;
    }

    auto it = player2pos_.find(player_id);
    if(it != player2pos_.end()){
        auto& [old_y, old_x] = it->second;
        LOG_DEBUG("已经在地图，旧位置：{},{}", old_x, old_y);
        map_[old_y][old_x] = 0;
        old_x = x;
        old_y = y;
    }else{
        player2pos_.emplace(player_id, std::pair<int, int>(y, x));
    }
    
    map_[y][x] = player_id;
}

void GameMap::RemovePlayer(int player_id){
    auto it = player2pos_.find(player_id);
    if(it != player2pos_.end()){
        auto [y, x] = it->second;
        map_[y][x] = 0;
        player2pos_.erase(player_id);
    }
}

std::string GameMap::ShowMapInfo(int player_id){
    // for(auto& vec: map_){
    //     for(auto& v: vec){
    //         std::cout << v << " ";
    //     }
    //     std::cout << std::endl;
    // }

    int val = 0;

    std::string map = "";
    for(int i = 0; i <= length_ + 1; ++i){
        map += "**";
    }
    map += "\n";

    for(int i = 0; i <= length_; ++i){
        map += "* ";
        for(int j = 0; j <= width_; ++j){
            val = map_[i][j];
            if(val != 0){
                if(val == player_id){
                    map += "\033[32m" + std::to_string(map_[i][j]) + "\033[0m" + " ";
                }else{
                    map += "\033[31m" + std::to_string(map_[i][j]) + "\033[0m" + " ";
                }
            }else{
                map += std::to_string(map_[i][j]) + " ";
            }
            
        }
        map += "*\n";
    }

    for(int i = 0; i <= length_ + 1; ++i){
        map += "**";
    }
    map += "\n";

    return map;
}
